<template>
  <div class="app-container">
    <div class="calendar-container">
      <div class="calendar-header">
        <div class="calendar-title">{{ currentMonthYear }}</div>
        <div class="calendar-nav">
          <button class="nav-btn" @click="prevMonth">‹</button>
          <button class="nav-btn" @click="goToToday">今天</button>
          <button class="nav-btn" @click="nextMonth">›</button>
        </div>
      </div>
      <div class="calendar-weekdays">
        <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>
      </div>
      <div class="calendar-days">
        <div 
          v-for="day in calendarDays" 
          :key="day.date"
          class="calendar-day"
          :class="{
            'other-month': !day.isCurrentMonth,
            'today': day.isToday,
            'selected': day.date === selectedDate,
            'has-task': hasTask(day.date)
          }"
          @click="selectDate(day.date)"
        >
          {{ day.day }}
        </div>
      </div>
      <div class="selected-date">
        当前选择: {{ formattedSelectedDate }}
      </div>
    </div>

    <div class="tasks-sidebar">
      <div class="sidebar-title">学习进度</div>
      
      <div class="progress-section">
        <div class="progress-title">学习进度</div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
        </div>
        <div class="progress-text">{{ progressText }}</div>
      </div>
      
      <div class="current-date-tasks">
        {{ selectedDateTasksText }}
      </div>
      
      <div class="task-input">
        <input 
          type="text" 
          v-model="newTask" 
          placeholder="输入新的学习任务..." 
          @keyup.enter="addTask"
        >
        <button class="add-btn" @click="addTask">添加</button>
      </div>
      
      <div class="filter-tabs">
        <button 
          class="filter-tab" 
          :class="{ active: filter === 'all' }"
          @click="filter = 'all'"
        >
          全部
        </button>
        <button 
          class="filter-tab" 
          :class="{ active: filter === 'completed' }"
          @click="filter = 'completed'"
        >
          已完成
        </button>
      </div>
      
      <div class="task-list">
        <div v-if="filteredTasks.length > 0">
          <div class="task-item" v-for="task in filteredTasks" :key="task.id">
            <input 
              type="checkbox" 
              class="task-checkbox" 
              v-model="task.completed"
              @change="updateProgress"
            >
            <div class="task-content" :class="{ completed: task.completed }">
              {{ task.content }}
            </div>
            <button class="delete-btn" @click="deleteTask(task.id)">删除</button>
          </div>
        </div>
        <div class="empty-tasks" v-else>
          暂无任务，添加新的学习任务
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';

export default {
  name: 'StudyCalendar',
  setup() {
    const currentDate = ref(new Date());
    const selectedDate = ref('');
    const newTask = ref('');
    const tasks = ref([]);
    const filter = ref('all');
    
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    
    // 修复日期格式函数 - 使用本地时间而不是UTC时间
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    const currentMonthYear = computed(() => {
      return currentDate.value.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long' 
      });
    });
    
    const formattedSelectedDate = computed(() => {
      if (!selectedDate.value) return '未选择';
      const date = parseDate(selectedDate.value);
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        weekday: 'long'
      });
    });
    
    // 解析日期字符串为Date对象
    const parseDate = (dateString) => {
      const [year, month, day] = dateString.split('-').map(Number);
      return new Date(year, month - 1, day);
    };
    
    const selectedDateTasks = computed(() => {
      if (!selectedDate.value) return [];
      return tasks.value.filter(task => task.date === selectedDate.value);
    });
    
    const selectedDateTasksText = computed(() => {
      if (!selectedDate.value) return '请选择日期';
      
      const total = selectedDateTasks.value.length;
      const completed = selectedDateTasks.value.filter(task => task.completed).length;
      
      return `当天任务: ${completed}/${total} 已完成`;
    });
    
    const calendarDays = computed(() => {
      const year = currentDate.value.getFullYear();
      const month = currentDate.value.getMonth();
      
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      const firstDayIndex = firstDay.getDay();
      const daysInMonth = lastDay.getDate();
      
      const prevMonthLastDay = new Date(year, month, 0).getDate();
      
      const days = [];
      
      // 添加上个月的日期
      for (let i = firstDayIndex; i > 0; i--) {
        const date = new Date(year, month - 1, prevMonthLastDay - i + 1);
        days.push({
          day: prevMonthLastDay - i + 1,
          date: formatDate(date),
          isCurrentMonth: false,
          isToday: false
        });
      }
      
      // 添加当前月的日期
      const today = new Date();
      const todayFormatted = formatDate(today);
      
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month, i);
        const dateFormatted = formatDate(date);
        days.push({
          day: i,
          date: dateFormatted,
          isCurrentMonth: true,
          isToday: dateFormatted === todayFormatted
        });
      }
      
      // 添加下个月的日期
      const totalCells = 42;
      const nextDays = totalCells - days.length;
      
      for (let i = 1; i <= nextDays; i++) {
        const date = new Date(year, month + 1, i);
        days.push({
          day: i,
          date: formatDate(date),
          isCurrentMonth: false,
          isToday: false
        });
      }
      
      return days;
    });
    
    const completedTasks = computed(() => {
      return tasks.value.filter(task => task.completed).length;
    });
    
    const progressPercentage = computed(() => {
      if (tasks.value.length === 0) return 0;
      return Math.round((completedTasks.value / tasks.value.length) * 100);
    });
    
    const progressText = computed(() => {
      return `已完成 ${completedTasks.value} / 总计 ${tasks.value.length} 个任务`;
    });
    
    const filteredTasks = computed(() => {
      const dateTasks = selectedDateTasks.value;
      switch (filter.value) {
        case 'completed':
          return dateTasks.filter(task => task.completed);
        default:
          return dateTasks;
      }
    });
    
    const hasTask = (date) => {
      return tasks.value.some(task => task.date === date);
    };
    
    const selectDate = (date) => {
      selectedDate.value = date;
    };
    
    const addTask = () => {
      if (newTask.value.trim() === '' || !selectedDate.value) return;
      
      tasks.value.push({
        id: Date.now(),
        content: newTask.value,
        completed: false,
        date: selectedDate.value
      });
      
      newTask.value = '';
      saveTasks();
    };
    
    const deleteTask = (id) => {
      tasks.value = tasks.value.filter(task => task.id !== id);
      saveTasks();
    };
    
    const updateProgress = () => {
      saveTasks();
    };
    
    const saveTasks = () => {
      localStorage.setItem('studyTasks', JSON.stringify(tasks.value));
    };
    
    const prevMonth = () => {
      currentDate.value = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() - 1,
        1
      );
    };
    
    const nextMonth = () => {
      currentDate.value = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() + 1,
        1
      );
    };
    
    const goToToday = () => {
      currentDate.value = new Date();
      selectedDate.value = formatDate(new Date());
    };
    
    onMounted(() => {
      selectedDate.value = formatDate(new Date());
      
      // 从本地存储加载任务
      const savedTasks = localStorage.getItem('studyTasks');
      if (savedTasks) {
        tasks.value = JSON.parse(savedTasks);
      }
    });
    
    return {
      currentDate,
      selectedDate,
      newTask,
      tasks,
      filter,
      weekdays,
      currentMonthYear,
      calendarDays,
      formattedSelectedDate,
      selectedDateTasks,
      selectedDateTasksText,
      completedTasks,
      progressPercentage,
      progressText,
      filteredTasks,
      hasTask,
      selectDate,
      addTask,
      deleteTask,
      updateProgress,
      prevMonth,
      nextMonth,
      goToToday
    };
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Arial, sans-serif;
}
.app-container {
  display: flex;
  width: 66.66vw;
  max-width: 1000px;
  gap: 20px;
  margin: 0 auto;
  padding: 20px;
}
.calendar-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  flex: 1;
  overflow: hidden;
}
.tasks-sidebar {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  width: 300px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.calendar-header {
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  padding: 15px;
  text-align: center;
}
.calendar-title {
  font-size: 1.3rem;
  font-weight: 600;
  margin-bottom: 8px;
}
.calendar-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.nav-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  transition: all 0.2s ease;
}
.nav-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}
.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #f8f9fa;
  padding: 8px 0;
  border-bottom: 1px solid #eaeaea;
}
.weekday {
  text-align: center;
  font-weight: 600;
  color: #6c757d;
  font-size: 0.85rem;
}
.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background: #eaeaea;
}
.calendar-day {
  background: white;
  height: 45px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}
.calendar-day:hover {
  background: #f0f5ff;
}
.calendar-day.other-month {
  color: #adb5bd;
}
.calendar-day.today {
  background: #e3f2fd;
  color: #1976d2;
  font-weight: 600;
}
.calendar-day.selected {
  background: #1976d2;
  color: white;
}
.calendar-day.has-task::after {
  content: '';
  position: absolute;
  bottom: 4px;
  right: 4px;
  width: 6px;
  height: 6px;
  background: #4caf50;
  border-radius: 50%;
}
.selected-date {
  padding: 12px;
  text-align: center;
  background: #f8f9fa;
  border-top: 1px solid #eaeaea;
  font-weight: 500;
  color: #495057;
}
.sidebar-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}
.progress-section {
  margin-bottom: 20px;
}
.progress-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
}
.progress-bar {
  height: 10px;
  background: #e0e0e0;
  border-radius: 5px;
  margin-bottom: 8px;
  overflow: hidden;
}
.progress-fill {
  height: 100%;
  background: #4caf50;
  border-radius: 5px;
  transition: width 0.3s ease;
}
.progress-text {
  text-align: center;
  font-size: 0.9rem;
  color: #666;
}
.task-input {
  display: flex;
  margin-bottom: 15px;
}
.task-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px 0 0 6px;
  font-size: 0.9rem;
}
.add-btn {
  background: #4caf50;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 0 6px 6px 0;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.2s;
}
.add-btn:hover {
  background: #45a049;
}
.filter-tabs {
  display: flex;
  margin-bottom: 15px;
  background: #f5f5f5;
  border-radius: 6px;
  overflow: hidden;
}
.filter-tab {
  flex: 1;
  padding: 8px;
  text-align: center;
  background: none;
  border: none;
  cursor: pointer;
  transition: background 0.2s;
}
.filter-tab.active {
  background: #4caf50;
  color: white;
}
.task-list {
  flex: 1;
  overflow-y: auto;
}
.task-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.task-checkbox {
  margin-right: 10px;
  width: 18px;
  height: 18px;
}
.task-content {
  flex: 1;
  font-size: 0.95rem;
}
.task-content.completed {
  text-decoration: line-through;
  color: #888;
}
.delete-btn {
  background: none;
  border: none;
  color: #f44336;
  cursor: pointer;
  font-size: 0.9rem;
}
.empty-tasks {
  text-align: center;
  color: #999;
  font-style: italic;
  margin-top: 20px;
}
.current-date-tasks {
  margin-top: 10px;
  font-size: 0.9rem;
  color: #666;
  text-align: center;
}
</style>